package com.yuanqiworld.vw.service;

import com.yuanqiworld.vw.domain.AuthorityInfo;
import com.yuanqiworld.vw.domain.RoleInfo;
import com.yuanqiworld.vw.domain.UserInfo;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户验证密码类.
 */
public class UserServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            UserInfo userInfo = UserInfo.findUserInfoesByUsername(username).getSingleResult();
            Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
            for (RoleInfo roleInfo : userInfo.getRoles()) {
                for (AuthorityInfo authorityInfo : roleInfo.getAuthorities()) {
                    authorities.add(new SimpleGrantedAuthority(authorityInfo.getAuthorityName()));
                }
            }
            return new User(userInfo.getUsername(),userInfo.getPassword(), userInfo.isEnabled(), true, true, true, authorities);
        } catch (EmptyResultDataAccessException e) {
            throw new UsernameNotFoundException("");
        }
    }
}
